package packed_widgets

import (
	"strconv"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/widget"
	"github.com/spf13/cast"
)

type NumEntry struct {
	*fyne.Container

	OnChange func(string)

	entry *widget.Entry
}

func (numEntry *NumEntry) IsEmpty() bool {
	return len(numEntry.entry.Text) == 0
}

func (numEntry *NumEntry) GetValue(defaultVal int) int {
	if len(numEntry.entry.Text) == 0 {
		return defaultVal
	}
	return cast.ToInt(numEntry.entry.Text)
}

func (numEntry *NumEntry) SetValue(val string) {
	numEntry.entry.Text = val
	numEntry.entry.Refresh()
}

func NewNumEntry(minVal, maxVal, defaultVal *int) *NumEntry {
	numEntry := &NumEntry{
		OnChange: func(s string) {},
		entry:    widget.NewEntry(),
	}

	if defaultVal != nil {
		numEntry.entry.SetText(cast.ToString(defaultVal))
	}

	numEntry.entry.OnChanged = func(s string) {
		if _, err := strconv.Atoi(s); err != nil {
			numEntry.entry.SetText("")
			return
		}

		numEntry.OnChange(s)
	}

	numEntry.Container = container.NewHBox(
		NewButton("-", nil, func() {
			if len(numEntry.entry.Text) == 0 {
				val := 0
				if minVal != nil && *minVal > val {
					val = *minVal
				}
				numEntry.entry.SetText(cast.ToString(val))
				return
			}

			val := cast.ToInt(numEntry.entry.Text) - 1
			if minVal != nil && val < *minVal {
				val = *minVal
			}
			numEntry.entry.SetText(cast.ToString(val))
		}),
		numEntry.entry,
		NewButton("+", nil, func() {
			if len(numEntry.entry.Text) == 0 {
				val := 0
				if minVal != nil && *minVal > val {
					val = *minVal
				}
				numEntry.entry.SetText(cast.ToString(val))
				return
			}

			val := cast.ToInt(numEntry.entry.Text) + 1
			if maxVal != nil && val > *maxVal {
				val = *maxVal
			}
			numEntry.entry.SetText(cast.ToString(val))
		}),
	)

	return numEntry
}
